function br2nl(str) {
    return str.replace(/<br\s*\/?>/mg,"\n");
}

function ajax(data, callback) {
    $.ajax({
        url: root + "ajax.php",
        async: false,
        type: "POST",
        data: data,
        success: function(output) {
            var result = jQuery.parseJSON(output);
            callback(result);
        }
    });
}

function checkLogin(username, password){
    var data = {
        action : 'checkLogin',
        params: {
            username: username,
            password: password
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        if (data.result==0){
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function checkAdd_task(title,client,responsible,deadline,type,status,priority,description,duration){
    var data = {
        action : 'checkAdd_task',
        params: {
            title: title,
            client: client, 
            responsible: responsible,
            deadline: deadline,
            type: type,
            status: status,
            priority: priority,
            description: description,
            duration: duration
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        $(".tableForm label").css("color", 'black');
        $(".tableForm label").css("font-weight", 'normal');
        if (data.result==0){
            for (var key in data.bad_fields)
            {
                var selector = data.bad_fields[key];
                $("label[for="+selector+"]").css("color","red");
                $("label[for="+selector+"]").css("font-weight","bold");
            }
            
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function changeRecordsPerPage(records, variable){
    var data = {
        action : 'changeRecords_per_page',
        params: {
            records: records,
            variable: variable
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            var page = variable.replace("_pager",'');
            if (page == 'cash')
                page = 'state_of_cash';
            document.location.href = root + "?input="+page+"&page=0";
        } 
    });
}

function order(order, variable, description){
    var data = {
        action : 'changeOrderOfRows',
        params: {
            order: order,
            variable: variable,
            description: description
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            var page = variable.replace("_order",'');
            if (page == 'cash')
                page = 'state_of_cash';
            document.location.href = root + "?input="+page+"&page=0";
        } 
    });
}

function filter(filter, value, variable){
    if (value==-1){
        cancelFilter(filter, variable);
        return;
    }
    
    var data = {
        action : 'addFilter',
        params: {
            filter: filter,
            value: value,
            variable: variable
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            var page = variable.replace("_filter",'');
            if (page == 'cash')
                page = 'state_of_cash';
            document.location.href = root + "?input="+page+"&page=0";
        } 
    });
}

function cancelFilter(filter, variable){
    var data = {
        action : 'cancelFilter',
        params: {
            filter: filter,
            variable: variable
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            var page = variable.replace("_filter",'');
            if (page == 'cash')
                page = 'state_of_cash';
            document.location.href = root + "?input="+page+"&page=0";
        } 
    });
}

function setFulltext(search, variable) {
    var data = {
        action : 'setFulltext',
        params: {
            search: search,
            variable: variable
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            var page = variable.replace("_fulltext",'');
            if (page == 'cash')
                page = 'state_of_cash';
            document.location.href = root + "?input="+page+"&page=0";
        } 
    });
}

function cancelFulltext(variable){
    var data = {
        action : 'cancelFulltext',
        params: {
            variable: variable
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            var page = variable.replace("_fulltext",'');
            if (page == 'cash')
                page = 'state_of_cash';
            document.location.href = root + "?input="+page+"&page=0";
        } 
    });
}

function deleteTask(id){
    var result = confirm("Do you really want to delete this task?");
    if (result) {
        var data = {
            action : 'deleteTask',
            params: {
                taskId: id
            }
        }
    
        ajax(data, function (data) {
            if (data.result==1){
                document.location.href = root + "?input=list_of_tasks";
            } else {
                alert("Deleting failed!");
            }
        });
    }
}

function deletePost(id){
    var result = confirm("Do you really want to delete this post?");
    if (result) {
        var data = {
            action : 'deletePost',
            params: {
                postId: id
            }
        }
    
        ajax(data, function (data) {
            if (data.result==1){
                document.location.reload()
            } else {
                alert("Deleting failed!");
            }
        });
    }
}

function editPost(id){
    var data = {
        action : 'getPostData',
        params: {
            postId: id
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            $('html, body').animate({
                scrollTop:0
            }, 'fast');
            openOverlay('overlayEditPost','editPostForm');
            var content = '';
            content += '<form class="editPostForm" method="post" action="'+root+'?input=edit_task&task='+data.post.task_id+'#'+data.post.task_phorum_id+'">';
            content += '<h2>Edit post:</h2>';
            content += '<textarea cols="53" rows="10" name="phorum[text]">'+br2nl(data.post.text)+'</textarea>';
            content += '<input name="phorum[task_phorum_id]" type="hidden" value="'+data.post.task_phorum_id+'" />';
            content += '<input name="action" value="edit_post" type="hidden" /><br/>';
            content += '<input value="Save" type="submit" />';
            content += '</form>';
            $("body").append(content);
        } else {
            alert("This post does not exist!");
        }
    });
}

function deleteRecordPost(id, rid){
    var result = confirm("Do you really want to delete this post?");
    if (result) {
        var data = {
            action : 'deleteRecordPost',
            params: {
                postId: id
            }
        }
    
        ajax(data, function (data) {
            if (data.result==1){
                document.location.href = root + "?input=tsdr_more&tsdr_id="+rid;
            } else {
                alert("Deleting failed!");
            }
        });
    }
}

function editRecordPost(id, rid){
    var data = {
        action : 'getRecordPostData',
        params: {
            postId: id
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            $('html, body').animate({
                scrollTop:0
            }, 'fast');
            openOverlay('overlayEditPost','editPostForm');
            var content = '';
            content += '<form class="editPostForm" method="post" action="'+root+'?input=tsdr_more&tsdr_id='+rid+'">';
            content += '<h2>Edit post:</h2>';
            content += '<textarea cols="80" rows="10" name="phorum[text]">'+br2nl(data.post.text)+'</textarea>';
            content += '<input name="phorum[record_phorum_id]" type="hidden" value="'+data.post.record_phorum_id+'" />';
            content += '<input name="action" value="edit_post" type="hidden" /><br/>';
            content += '<input value="Save" type="submit" />';
            content += '</form>';
            $("body").append(content);
        } else {
            alert("This post does not exist!");
        }
    });
}

function openOverlay(id,removeElement) {
    var classOfRemoveElement;
    var idOfOverlay;
    if (id!=undefined && id!='undefined' && id!= null)
        idOfOverlay = id;
    else 
        idOfOverlay = '';
    if (removeElement!=undefined && removeElement!='undefined' && removeElement!= null)
        classOfRemoveElement = removeElement;
    else 
        classOfRemoveElement = '';
    var content;
    var height = $("body").css("height");
    content = '<div class="overlay" id="'+idOfOverlay+'" onclick="closeOverlay(\''+idOfOverlay+'\', \''+classOfRemoveElement+'\');"></div>';
    $("body").append(content);
    if (idOfOverlay != '')
        $("#"+idOfOverlay).height(height);
    else
        $(".overlay").height(height);
}

function closeOverlay(id, removeElement) {
    if (id!='')
        $('#'+id).remove();
    else
        $('.overlay').remove();
    
    if (removeElement != '')
        $('.'+removeElement).remove();
}

function checkIt(status){
    var st = $('#'+status).attr('checked');
    if (st == 'checked')
        $('.clientSelector').attr("checked", 'checked');
    else
        $('.clientSelector').removeAttr("checked");
}

function makeFloat(element, countOfDecimal){
    if (countOfDecimal == null)
        countOfDecimal = 2;
    $(element).each(function(index) {
        var val = $(this).val();
        val = val.replace(",",".");
        val = parseFloat(val);
        if (isNaN(val))
            val = 0.00;
        val = val.toFixed(countOfDecimal);
        $(this).val(val);
    });
}

function checkAdd_client(name, active){
    var data = {
        action : 'checkAdd_client',
        params: {
            name: name,
            active: active
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        $(".tableForm label").css("color", 'black');
        $(".tableForm label").css("font-weight", 'normal');
        if (data.result==0){
            for (var key in data.bad_fields)
            {
                var selector = data.bad_fields[key];
                $("label[for="+selector+"]").css("color","red");
                $("label[for="+selector+"]").css("font-weight","bold");
            }
            
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function submitForm(id){
    $("#"+id).submit();
} 

function checkAdd_user(name, surname, login, password, client, userlevel, active){
    var data = {
        action : 'checkAdd_user',
        params: {
            name: name,
            surname: surname,
            login: login,
            password: password,
            client: client,
            userlevel: userlevel,
            active: active
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        $(".tableForm label").css("color", 'black');
        $(".tableForm label").css("font-weight", 'normal');
        $(".tableForm label.hide").css("color", 'white');
        if (data.result==0){
            for (var key in data.bad_fields)
            {
                var selector = data.bad_fields[key];
                $("label[for="+selector+"]").css("color","red");
                $("label[for="+selector+"]").css("font-weight","bold");
            }
            
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function preprocessPassword(id){
    var val = $(id).val();
    if(!$.trim(val).length) { 
        return 'prazdneHeslo';
    } else {
        return val;
    }
}

function showAssociatedClients(value,client){
    $(".connected-list").css("height","200px");
    if (value==client)
        $("#associatedClientsForm").show();
    else
        $("#associatedClientsForm").hide();
}

function checkAdd_entry(date, amount, description){
    var data = {
        action : 'checkAdd_entry',
        params: {
            date: date,
            amount: amount,
            description: description
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        $(".tableForm label").css("color", 'black');
        $(".tableForm label").css("font-weight", 'normal');
        $(".tableForm label.hide").css("color", 'white');
        if (data.result==0){
            for (var key in data.bad_fields)
            {
                var selector = data.bad_fields[key];
                $("label[for="+selector+"]").css("color","red");
                $("label[for="+selector+"]").css("font-weight","bold");
            }
            
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function checkAdd_tariff(title, tariff, servis_tariff, unit, type_of_record, description){
    var data = {
        action : 'checkAdd_tariff',
        params: {
            title: title,
            tariff: tariff,
            servis_tariff: servis_tariff,
            unit: unit,
            type_of_record: type_of_record,
            description: description
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        $(".tableForm label").css("color", 'black');
        $(".tableForm label").css("font-weight", 'normal');
        $(".tableForm label.hide").css("color", 'white');
        if (data.result==0){
            for (var key in data.bad_fields)
            {
                var selector = data.bad_fields[key];
                $("label[for="+selector+"]").css("color","red");
                $("label[for="+selector+"]").css("font-weight","bold");
            }
            
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function checkAdd_record(date, client, type, amount, price, description, amount_original, tariff){
    var data = {
        action : 'checkAdd_record',
        params: {
            date: date,
            client: client,
            type: type,
            amount: amount,
            price: price,
            description: description,
            amount_original: amount_original,
            tariff: tariff
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        $(".tableForm label").css("color", 'black');
        $(".tableForm label").css("font-weight", 'normal');
        $(".tableForm label.hide").css("color", 'white');
        if (data.result==0){
            for (var key in data.bad_fields)
            {
                var selector = data.bad_fields[key];
                $("label[for=r"+selector+"]").css("color","red");
                $("label[for=r"+selector+"]").css("font-weight","bold");
            }
            
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function deleteRecord(id, location){
    var result = confirm("Do you really want to delete this record?");
    if (result) {
        var data = {
            action : 'deleteRecord',
            params: {
                recordId: id
            }
        }
    
        ajax(data, function (data) {
            if (data.result==1){
                if (location!=null)
                    document.location.href = root + "?input="+location;
                else
                    document.location.href = root + "?input=timesheets";
            } else {
                if (data.locked==1)
                    alert("This record is locked!");
                else
                    alert("Deleting failed!");
            }
        });
    }
}

function changeClientFilter(value, rememberItem){
    var remember = 0;
    if ($("#"+rememberItem).is(':checked')){
        remember = 1;
    }
    var data = {
        action : 'changeClientFilter',
        params: {
            value: value,
            remember: remember
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            var url = (document.URL);
            if (url.search("&clear_tasks_order=1") > -1){
                url = url.replace("&clear_tasks_order=1", "");
                document.location.href = url;
            } else {
                document.location.reload();
            }
        } 
    });
}

function rememberClientFilter(remember){
    var data = {
        action : 'rememberClientFilter',
        params: {
            remember: remember
        }
    }
    
    ajax(data, function (data) {
        
        });
}

function userListOfClient(client){
    var data = {
        action : 'userListOfClient',
        params: {
            client: client
        }
    }
    
    ajax(data, function (data) {
        if (data.result==1){
            $("#selectedUser").empty();
            $("#selectedUser").append('<option value="">Please select</option>');
            $("#selectedUser").append(data.options);
        } else {
            $("#selectedUser").empty();
            $("#selectedUser").append('<option value="">Please select</option>');
        }
    });
}

function taskListOfClient(client){
    if (client != "") {
    
        var data = {
            action : 'taskListOfClient',
            params: {
                client: client
            }
        }

        ajax(data, function (data) {
            if (data.result==1){
                $("#selectedTask").empty();
                $("#selectedTask").append('<option value="">Please select</option>');
                $("#selectedTask").append(data.options);
            } else {
                $("#selectedTask").empty();
                $("#selectedTask").append('<option value="">Please select</option>');
            }
        });
    } else {
        $("#selectedTask").empty();
        $("#selectedTask").append('<option value="">Please select</option>');
    }
}

function deleteEntry(id){
    var result = confirm("Do you really want to delete this cashentry?");
    if (result) {
        var data = {
            action : 'deleteEntry',
            params: {
                entryId: id
            }
        }
    
        ajax(data, function (data) {
            if (data.result==1){
                document.location.href = root + "?input=state_of_cash";
            } else {
                if (data.locked==1)
                    alert("This entry is locked!");
                else
                    alert("Deleting failed!");
            }
        });
    }
}

function fillDescription(target, tariff) {
    if ((tariff == 7) || (tariff == 8)) {
        var data = {
            action : 'fillDescription',
            params: {
                tariffId: tariff
            }
        }
    
        ajax(data, function (data) {
            if (data.result==1){
                $(target).val();
                $(target).val(data.title);
            } 
        });
    }
}

function selectRow(id, originalClass){
    var selected = 'bgSelected';
    var element = '#row_'+id;
    $('.row').removeClass(selected);
    if ($(element).hasClass(selected)){
        $(element).removeClass(selected);
    } else {
        $(element).addClass(selected);
    }
}

function unexpended(date, client) {
    var data = {
        action : 'unexpended',
        params: {
            date: date,
            client: client
        }
    }
    
    //console.log(data);
    
    ajax(data, function (data) {
        $("#unexpended").empty();
        $("#unexpended").append('<b>Unexpended:</b><br/>' + data.value);
    });
}

function checkAdd_expense(user, expense, from){
    var data = {
        action : 'checkAdd_expense',
        params: {
            user: user,
            fixed_expense: expense,
            from: from
        }
    }
    
    var result = false;
    
    ajax(data, function (data) {
        $(".tableForm label").css("color", 'black');
        $(".tableForm label").css("font-weight", 'normal');
        $(".tableForm label.hide").css("color", 'white');
        if (data.result==0){
            for (var key in data.bad_fields)
            {
                var selector = data.bad_fields[key];
                $("label[for="+selector+"]").css("color","red");
                $("label[for="+selector+"]").css("font-weight","bold");
            }
            
            alert(data.error);
            result = false;
        } else {
            result = true;
        }
    });

    return result;
}

function getRentabilityTablePerServismen(taskId) {
    var position = $('.positionHandler').offset();
    var width = parseInt(position['left']) - 100 ;
    $("#rentOverlayContent").css("width", width + 'px');
    $("#rentOverlay").show();
    
    var data = {
        action : 'getRentabilityTablePerServismen',
        params: {
            taskId : taskId
        }
    }
    
    ajax(data, function (data) {
        if (data.result==0){
            alert(data.error);
        } else {
            if (data.output != ''){
                $("#rentOverlayContent").html(data.output);
                $("#rentOverlay").css("height", "auto");
            }
        }
    });
    
}

function hideRentabilityOverlay() {
    $("#rentOverlayContent").css("background", 'url("'+root+'images/ajax-loader.gif") no-repeat center center white');
    $("#rentOverlayContent").empty();
    $("#rentOverlay").hide();
}

function getRentabilityTablePerTasks(servisman, period) {
    $("#rentOverlayContent").css("background", 'url("'+root+'images/ajax-loader.gif") no-repeat center center white');
    $("#rentOverlayContent").empty();
    $("#rentOverlay").css("height", "200px");
    var position = $('.positionHandler').offset();
    var width = parseInt(position['left']) - 100 ;
    $("#rentOverlayContent").css("width", width + 'px');
    $("#rentOverlay").show();
    
    var data = {
        action : 'getRentabilityTablePerTasks',
        params: {
            userId: servisman,
            period: period
        }
    }
    
    ajax(data, function (data) {
        if (data.result==0){
            alert(data.error);
        } else {
            if (data.output != ''){
                $("#rentOverlayContent").css("background", "white");
                $("#rentOverlayContent").html(data.output);
                $("#rentOverlayContent").css("overflow", "auto");
                var height = parseInt($(window).height()) - 80;
                $("#rentOverlay").css("height", height+"px");
            }
        }
    });
    
}

function count_tsdr_description_length(element, max_length_predefined){
    var att_name = element.attr("name");
    if (att_name == 'record[description]') {
        var max_length = element.attr("maxlength");
        if (typeof max_length == "undefined"){
            max_length = max_length_predefined;
        } 
        max_length = parseInt(max_length);
        var value = element.val();
        var length = value.length;
        var free_chars = max_length - length;
        if (length > max_length) {
            value = value.substr(0,max_length);
            element.val(value);
            free_chars = 0;
        }
        
        $(".free_chars_counter").find("span.free_chars").remove();
        $(".free_chars_counter").append('<span class="free_chars">'+free_chars+'</span>');
    }
}